package lib

import (
	"GameServer/Common/data"
	"GameServer/Common/utils"
	"GameServer/Game/errors"
	"GameServer/Game/m"
)

func MagicFurnace(from string, u *m.User, mData map[int64]int64, PSend func(interface{}) error) (uProp *m.UpdateProp, resGoods *m.Goods, err error) {

	if !checkEnoughHeroGoods(u, mData) {
		err = errors.NewErrcode(data.Errcode.NoHeroGoods, "卡片不足")
		return
	}

	// 章节  默认第一章节
	var page int64 = 1

	for key, _ := range mData {
		mtpl, ok := data.Get("MagicFurnaces", uint64(key))
		if !ok {
			err = errors.NewErrcode(data.Errcode.NoHeroGoods, "卡片不足")
			return nil, nil, err
		}
		mt := mtpl.(data.MagicFurnace)
		if page < int64(mt.Page) {
			page = int64(mt.Page)
		}
	}

	// 先消耗
	for id, num := range mData {
		u.Heros().CostHeroGoods(id, num)
	}

	goodsTid, err := furnace(page)
	if err != nil {
		return
	}

	uProp, resGoodsList, _, err := GiveGoodsByKv(from, u, m.BaseKV{Key: goodsTid, Val: 1}, PSend)
	if err != nil {
		return
	}
	resGoods = resGoodsList[0]
	return
}

func checkEnoughHeroGoods(u *m.User, mData map[int64]int64) (ok bool) {
	heros := u.Heros()
	star := 0
	for id, num := range mData {
		hgoods, ok := heros.GetHeroGoodsByGoodsTid(id)
		if !ok {
			return ok
		}
		if num+1 >= hgoods.Num {
			return false
		}
		goodsTpl, ok := data.Get("Goods", uint64(id))
		if !ok {
			return ok
		}
		goodsT := goodsTpl.(data.Good)
		star += int(goodsT.Star) * int(num)
	}
	if star < 10 {
		return false
	}
	return true
}

func furnace(page int64) (goodsTid int64, err error) {
	f := func(val interface{}) bool {
		t := val.(data.MagicFurnace)
		if int64(t.Page) <= page {
			return true
		}
		return false
	}

	list, ok := data.Foreachs("MagicFurnaces", f)
	if !ok || len(list) == 0 {
		err = errors.NewErrcode(data.Errcode.ConfigNotFound, "没有找到MagicFurnaces配置表")
		return
	}

	var weightList []data.WeightV

	for _, item := range list {
		v := item.(data.MagicFurnace)
		weightList = append(weightList, data.WeightV{Weight: uint64(v.Weight), Value: v.Id})
	}

	w := utils.RandomWeight(weightList)
	goodsTid = utils.Int64(w.Value)
	return
}
